'use strict';

const BaseController = require('./base');
const { createRule } = require('../validator/price')
const { success, commonErr } = require('../extend/helper');


class PriceController extends BaseController {

    /**
     * 列表
     */
     async list() {
		const page = parseInt(this.ctx.query.page) ? parseInt(this.ctx.query.page) : 0;
		const size = parseInt(this.ctx.query.size) ? parseInt(this.ctx.query.size) : 15;
		const {rows, count} = await this.ctx.model.ThemeBanner.findAndCountAll({
			order: [
				['index', 'desc']
			],
			offset: page * size,
			limit: size
		});
		success({beans: {
			rows, count, page, size

		}})
    
    }
        
    /**
     * 新增
     */
    async add() {
		const data = this.ctx.request.body;
		const error = this.app.validator.validate(createRule, data);
		error && commonErr({beans: error});
		const res = await this.ctx.model.ThemeBanner.create(data);
		success();
    }

    /**
     * 编辑
     */
    async edit() {
		const data = this.ctx.request.body;
		const error = this.app.validator.validate(createRule, data);
		error && commonErr({beans: error});
		const id = this.ctx.params.id;
		await this.ctx.model.ThemeBanner.update(data, {where: {id}});
		success();
    }

    /**
     * 删除
     */
    async delete() {
		const banner = await this.getObject();
		banner.destroy();
		success();
    }

    /**
     * 切换按钮
     */
    async online() {
        const banner = await this.getObject();
        await this.onlineSwitch(banner);
        success();  
    }

    async getObject() {
        const id = this.ctx.params.id;
        const banner = await this.ctx.model.ThemeBanner.findByPk(id);
        if (!banner) {
            commonErr(`轮播图不存在`);
        }
        return banner;
    }

}

module.exports = PriceController;